package com.lenovo.gpsautotest.AMap;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.AMapLocationQualityReport;
import com.lenovo.gpsautotest.CheckPermissionsActivity;
import com.lenovo.gpsautotest.R;
import com.lenovo.gpsautotest.SpUtils;
import com.lenovo.gpsautotest.Utils;
import com.mixiaoxiao.smoothcompoundbutton.SmoothRadioGroup;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class AMapActivity extends CheckPermissionsActivity implements AMapLocationListener {
    private static final String TAG = AMapActivity.class.getSimpleName();
    //声明mlocationClient对象
    public AMapLocationClient mLocationClient=null;
    //声明mLocationOption对象
    public AMapLocationClientOption mLocationOption = null;
    @BindView(R.id.result)
    TextView tvResult;
    @BindView(R.id.et_longitude)
    EditText etLongitude;
    @BindView(R.id.et_latitude)
    EditText etLatitude;
    @BindView(R.id.rg_start)
    SmoothRadioGroup rgStartWay;
    @BindView(R.id.millisecond_between_sessions)
    EditText etIntervalTime;
    @BindView(R.id.btn_start)
    Button btnStart;
    @BindView(R.id.btn_stop)
    Button btnStop;
    @BindView(R.id.et_session_times)
    EditText etSessionTimes;
    @BindView(R.id.overtime)
    EditText etOvertime;
    @BindView(R.id.retry_times)
    EditText etRetryTimes;


    @OnClick(R.id.btn_start)
    void start() {
        //判断输入参数齐全
        if (etLatitude.getText().toString().isEmpty()) {
            Toast.makeText(this, getResources().getString(R.string.lack_latitude_warning),
                    Toast.LENGTH_SHORT).show();
            return;
        }
        if (etLongitude.getText().toString().isEmpty()) {
            Toast.makeText(this, getResources().getString(R.string.lack_longitude_warning),
                    Toast.LENGTH_SHORT).show();
            return;
        }
        if (etIntervalTime.getText().toString().isEmpty()) {
            Toast.makeText(this, getResources().getString(R.string.lack_milliseconds_warning),
                    Toast.LENGTH_SHORT).show();
            return;
        }

        //循环次数
        int times = Integer.parseInt(etSessionTimes.getText().toString().trim());
        //间隔时间
        int interval_time = Integer.parseInt(etIntervalTime.getText().toString().trim());
        //超时时间
        int overtime = Integer.parseInt(etOvertime.getText().toString().trim());
        //重试次数
        int retry_times = Integer.parseInt(etRetryTimes.getText().toString().trim());

        btnStart.setEnabled(false);

        for(int i=0;i<times;i++){
            mLocationClient = new AMapLocationClient(this);
            mLocationClient.setLocationListener(this);
            //设置定位参数
            if (mLocationOption == null) {
                mLocationOption = new AMapLocationClientOption();
            }

            //设置发起定位请求的时间间隔
            //单位：毫秒
            //默认值：2000毫秒
            mLocationOption.setInterval(2000);
            //仅设备定位模式： 在这种模式下，将只使用卫星定位。
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Device_Sensors);
            //设置是否使用缓存策略, 默认为true 使用缓存策略
            mLocationOption.setLocationCacheEnable(false);
            // 设置是否单次定位
            mLocationOption.setOnceLocation(true);

            mLocationClient.setLocationOption(mLocationOption);
            mLocationClient.startLocation();

        }


    }

    @OnClick(R.id.btn_stop)
    void stop() {
        if(null!=mLocationClient){
            mLocationClient.stopLocation();
            mLocationClient.onDestroy();
        }
        tvResult.setText("定位已停止");
        btnStart.setEnabled(true);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        initListener();
        initData();
    }

    private void initData() {
        tvResult.setVisibility(View.VISIBLE);
    }

    private void initListener() {
        rgStartWay.setOnCheckedChangeListener(new SmoothRadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SmoothRadioGroup smoothRadioGroup, int checkedId) {
                switch (checkedId) {
                    case R.id.cold_start:
                        SpUtils.setStartWay(AMapActivity.this, SpUtils.COLD_START);
                        break;
                    case R.id.hot_start:
                        SpUtils.setStartWay(AMapActivity.this, SpUtils.HOT_START);
                        break;
                }
            }
        });
    }

    @Override
    public void onLocationChanged(AMapLocation location) {
        StringBuffer sb = new StringBuffer();
        //errCode等于0代表定位成功，其他的为定位失败，具体的可以参照官网定位错误码说明
        if (location.getErrorCode() == 0) {
            sb.append("定位成功" + "\n");
            sb.append("定位类型: " + location.getLocationType() + "\n");
            sb.append("经    度    : " + location.getLongitude() + "\n");
            sb.append("纬    度    : " + location.getLatitude() + "\n");
            sb.append("精    度    : " + location.getAccuracy() + "米" + "\n");
            sb.append("提供者    : " + location.getProvider() + "\n");
            double inputLatitude = Double.parseDouble(etLatitude.getText().toString().trim());
            double inputLongitude = Double.parseDouble(etLongitude.getText().toString().trim());
            sb.append("经纬度距离    :" + Utils.getDistance(inputLatitude, inputLongitude,
                    location.getLatitude(), location.getLongitude()) + "\n");

            sb.append("速    度    : " + location.getSpeed() + "米/秒" + "\n");
            sb.append("角    度    : " + location.getBearing() + "\n");
            //定位完成的时间
            sb.append("定位时间: " + Utils.formatUTC(location.getTime(), "yyyy-MM-dd HH:mm:ss") + "\n");
        } else {
            //定位失败
            sb.append("定位失败" + "\n");
            sb.append("错误码:" + location.getErrorCode() + "\n");
            sb.append("错误信息:" + location.getErrorInfo() + "\n");
            sb.append("错误描述:" + location.getLocationDetail() + "\n");
        }
        sb.append("***定位质量报告***").append("\n");
        sb.append("* WIFI开关：").append(location.getLocationQualityReport().isWifiAble() ? "开启" :
                "关闭").append("\n");
        sb.append("* GPS状态：").append(getGPSStatusString(location.getLocationQualityReport().getGPSStatus())).append("\n");
        sb.append("* GPS星数：").append(location.getLocationQualityReport().getGPSSatellites()).append("\n");
        sb.append("****************").append("\n");
        //定位之后的回调时间
        sb.append("回调时间: " + Utils.formatUTC(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss") + "\n");
        sb.append("GPS卫星： " + location.getSatellites() + "\n");
        sb.append("*********Complete Result********").append("\n");
        sb.append(location.toStr(1) + "\n");
        sb.append(location.toStr(2) + "\n");
        sb.append(location.toStr(3) + "\n");
        tvResult.setText(sb.toString());
    }

    /**
     * 获取GPS状态的字符串
     *
     * @param statusCode GPS状态码
     * @return
     */
    private String getGPSStatusString(int statusCode) {
        String str = "";
        switch (statusCode) {
            case AMapLocationQualityReport.GPS_STATUS_OK:
                str = "GPS状态正常";
                break;
            case AMapLocationQualityReport.GPS_STATUS_NOGPSPROVIDER:
                str = "手机中没有GPS Provider，无法进行GPS定位";
                break;
            case AMapLocationQualityReport.GPS_STATUS_OFF:
                str = "GPS关闭，建议开启GPS，提高定位质量";
                break;
            case AMapLocationQualityReport.GPS_STATUS_MODE_SAVING:
                str = "选择的定位模式中不包含GPS定位，建议选择包含GPS定位的模式，提高定位质量";
                break;
            case AMapLocationQualityReport.GPS_STATUS_NOGPSPERMISSION:
                str = "没有GPS定位权限，建议开启gps定位权限";
                break;
        }
        return str;
    }


    @Override
    protected void onDestroy() {
        if (null != mLocationClient) {
            /**
             * 如果AMapLocationClient是在当前Activity实例化的，
             * 在Activity的onDestroy中一定要执行AMapLocationClient的onDestroy
             */
            mLocationClient.onDestroy();
            mLocationClient = null;
            mLocationOption = null;
        }
        super.onDestroy();
    }


}
